package com.wjj.sixinone.aspect;


import com.wjj.sixinone.common.pojo.entity.User;
import com.wjj.sixinone.common.pojo.log.ApiLogs;
import com.wjj.sixinone.common.util.AuthContextUtil;
import com.wjj.sixinone.common.util.CurrentIpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;


import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class ApiLogAspect {

    @Autowired
     private MongoTemplate mongoTemplate;

    @Pointcut("execution(* com.wjj.sixinone.controller.*.*(..))")
    public void logPointCut() {}

    @AfterReturning(value = "logPointCut()", returning = "rtv")
    public void afterLog(JoinPoint joinpoint, Object rtv) {
        try {

            // 创建 LogBean 实例
            ApiLogs logBean = new ApiLogs();
            logBean.setCreateTime(LocalDateTime.now());
            // 获取类名和方法名
            String className = joinpoint.getTarget().getClass().getSimpleName();
            String methodName = joinpoint.getSignature().getName();
            logBean.setClassName(className);
            logBean.setMethod(methodName);

            // 获取请求参数
            Object[] args = joinpoint.getArgs();
            StringBuilder reqParamBuilder = new StringBuilder();
            for (Object arg : args) {
                reqParamBuilder.append(arg).append(", ");
            }
            String reqParam = reqParamBuilder.toString();
            if (reqParam.length() > 2) {
                reqParam = reqParam.substring(0, reqParam.length() - 2);
            }
            logBean.setRequestQuery(reqParam);

            // 获取请求相关信息

            String ip = CurrentIpUtils.getUserIP();
            logBean.setIp(ip);
            // 获取当前用户信息
            User user = AuthContextUtil.get();
            if (user != null) {
                logBean.setUsername(user.getUsername());
            }

            // 保存到 MongoDB
            mongoTemplate.save(logBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
